package member.order.util;

import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.system.RuntimeData;
import m.system.util.NumberUtil;
import member.base.model.MoneyRecord;
import member.base.service.BusinessInfoService;
import member.base.service.LevelUpSetService;
import member.base.service.MemberInfoService;
import member.base.service.MoneyRecordService;
import member.order.model.MemberRecharge;
import member.order.model.OrderInfo;
import member.order.model.OrderPay;
import member.order.service.MemberRechargeService;
import member.order.service.OrderInfoService;

import java.util.List;

public class MoneyRecordUtil {
    /**
     * 添加充值记录
     */
    public static void addRecharge(MemberRecharge recharge) throws Exception {
        String busiOid=recharge.getOid(),memberOid=recharge.getMember().getOid();
        Double realMoney=recharge.getPayAmount(),giveMoney=recharge.getGiveAmount();
        Integer point=recharge.getGivePoint();
        //添加记录
        RuntimeData.getService(MoneyRecordService.class)
                .add(MoneyRecord.TypeRecharge, recharge.getType(), MemberRechargeService.class,busiOid,recharge.getOrderNo(),memberOid,realMoney,giveMoney,point);
        //更新会员数据
        RuntimeData.getService(MemberInfoService.class).updateAmount(memberOid,realMoney,giveMoney,point);
    }
    /**
     * 添加订单记录
     */
    public static void addOrder(OrderInfo order) throws Exception {
        String busiOid=order.getOid(),memberOid=order.getMember().getOid();
        List<OrderPay> pays= ModelQueryList.getModelList(OrderPay.class,new String[]{"*"},null, QueryCondition.eq("order.oid",busiOid));
        Double realMoney=0d,giveMoney=0d;
        int point=0;
        int pointRate = RuntimeData.getService(BusinessInfoService.class).getPointRate(order.getInputDate());
        for(OrderPay pay : pays) {
            point += NumberUtil.floor(pay.getPayAmount() * pointRate / 100).intValue();
            //添加记录
            RuntimeData.getService(MoneyRecordService.class)
                    .add(MoneyRecord.TypePayment, pay.getPayType(), OrderInfoService.class, busiOid,order.getOrderNo(), memberOid, -pay.getPayRealMoney(), -pay.getPayGiveMoney(), point);
            if (OrderInfo.PayTypeBalance.equals(pay.getPayType())) {
                //更新冻结金额
                RuntimeData.getService(MemberInfoService.class).updateFreeze(order.getMember().getOid(), -pay.getPayAmount());
                realMoney += pay.getPayRealMoney();
                giveMoney += pay.getPayGiveMoney();
            }
        }
        //更新会员数据
        RuntimeData.getService(MemberInfoService.class).addOrderAndUpdateAmount(memberOid,order.getPayAmount(),-realMoney, -giveMoney, point);
        //会员自动升级
        RuntimeData.getService(LevelUpSetService.class).autoUpSet(memberOid);
    }
}
